<template>
    <div class="login">
        <div class="wraper" v-if="ifidentity==true">
            <div class="tipinfo">
                <p>欢迎访问<vname :name="'明海物流'"></vname>公众号</p>
                <p class="small">您当前尚未进行账户绑定</p>
            </div>
            <div class="login_form">
                <div class="ipt_item">
                    <van-field v-model="account" left-icon="user-o" placeholder="请输入账号" />
                </div>
                <div class="ipt_item">
                    <van-field v-model="password" type="password" left-icon="closed-eye" placeholder="请输入密码" />
                </div>
                <div class="ipt_item">
                    <van-button type="info" round  class="logbtn" :disabled="logining" @click="bindlogin">立即绑定</van-button>
                </div>
            </div>
            <div class="bot_tip">
                <p>您好,欢迎您登录明海物流微信公众号</p>
                <p>如果您有任何需求,欢迎致电: 0755-26646158</p>
            </div>
        </div>
        <div class="wraper" v-if="ifidentity==false">
            <p class="tipwords">正在<vname :name="'检验账户'"></vname>信息 请稍等······</p>
        </div>
    </div>
</template>

<script>
import vname from "./vconsole.vue";
import { mapState } from "vuex";
export default {
    name: "login",
    components: {
        vname
    },
    data() {
        return {
            appid:'wx59bc2356eefcc028',//公众号appid
            redirectUrl:'http://m.mh.ink',//当前网址的url
            code:'',//用来获取openid的code
            state:'mhwl',
            account:'',
            password:'',
            logining:false,
            ifidentity:false,//微信账号是否验证过了
			unionid:'',
        }
    },
	computed:{
		...mapState({
			wxinfo: state=> state.user.wxinfo,
			openid: state=>state.user.token
		})
	},
    methods:{
        /**
         * 处理微信重定向 方便接收回传的code
         */
        getAuthCode:function(){
            let rdurl=encodeURIComponent(this.redirectUrl);
            let requrl='https://open.weixin.qq.com/connect/oauth2/authorize?appid='+this.appid+'&redirect_uri='+rdurl+'&response_type=code&scope=snsapi_userinfo&state='+this.state+'#wechat_redirect';
            window.location.href=requrl;
        },
        /**
         * 微信授权并获取openid
         */
        getUserInfo:function(){
            var _this=this;
            var loading = this.$toast.loading({
                duration:60000,
                message:'微信授权中,请稍等······'
            });
            this.axios.post('/public/getWxinfo',{code:this.code}).then(res=>{
                loading.clear();
                if(res.errno==0)
                {
                    if(res.data.status==1)
        			{
        				//已经绑定过了
        				var account = res.data.data;
						_this.unionid=res.data.data.unionid;
        				_this.$store.commit('user/setToken',account.openid);
        				_this.$store.commit('user/setAccount',account);
						if(_this.$route.query.redirect){
						   let redirect = _this.getQueryString('redirect');
						   if(redirect.indexOf('_')>-1)
						   {
                               var name='',param = '',val='';
                               name =redirect.split('_')[0];
							   param=redirect.split('_')[1];
							   val=redirect.split('_')[2];
                               if(param=='tctnrId')
                               {
                                   param='t_ctnrId';
                               }
                               var query = {};
                               query[param]=val;
							   _this.$router.replace({
							        path:'/'+name,
							        query:query
							   });
						   }else{
							   _this.$router.replace({
							        path:'/'+redirect,
							   });
						   }
						}else{
							_this.$toast(res.errmsg);
							setTimeout(function(){
								_this.$router.replace({
									path:'/profile'
								})
							},1000)
						}
        			}else{
        				//未绑定
						_this.ifidentity=true;
                        _this.$toast('微信授权成功,快绑定您的账号吧');
        				_this.$store.commit('user/setWxinfo',res.data.data);
						_this.unionid=res.data.data.unionid;
        			}
                }else{
        			_this.$toast(res.errmsg);
        		}
            }).catch(()=>{
                loading.clear();
                _this.$toast.fail('微信授权登录失败,请退出页面重试');
            })
        },
        /**
         * @param {Object} name
         * 从url中获取参数
         */
        getQueryString:function(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]);
            return null;
        },
		bindlogin:function(){
			if(this.openid)
			{
				this.simplelogin();
			}else{
				this.login();
			}
		},
		simplelogin:function(){
			var _this=this;
			var loading= this.$toast.loading({
			  message: '正在绑定...',
			  forbidClick: true,
			});
			_this.logining=true;
			this.axios.post('/public/binduser',{name:this.account,password:this.password,openid:this.openid,unionid:this.unionid}).then((res)=>{
			    loading.clear();
			    if(res.errno==0)
			    {
			        var account = res.data;
			        _this.$store.commit('user/setToken',account.openid);
			        _this.$store.commit('user/setAccount',account);
			        _this.$toast('已成功与微信账户绑定');
					if(_this.$route.query.redirect){
					   let redirect = _this.getQueryString('redirect');
					   if(redirect.indexOf('_')>-1)
					   {
					       var name='',param = '',val='';
					       name =redirect.split('_')[0];
						   param=redirect.split('_')[1];
						   val=redirect.split('_')[2];
					       if(param=='tctnrId')
					       {
					           param='t_ctnrId';
					       }
					       var query = {};
					       query[param]=val;
						   setTimeout(function(){
							   _this.$router.replace({
							        path:'/'+name,
							        query:query
							   });
						   },1000)
					   }else{
						   setTimeout(function(){
							   _this.$router.replace({
							        path:'/'+redirect,
							   });
						   },1000)
					   }
					}else{
						setTimeout(function(){
							_this.$router.replace({
								path:'/profile'
							})
						},1500)
					}
			    }else{
			        _this.logining=false;
			        _this.$toast.fail(res.errmsg);
			    }
			}).catch((err)=>{
			    _this.logining=false;
			    loading.clear(); 
			})
		},
        /**
         * 账号绑定
         */
        login:function(){
            var _this=this;
			if(!this.wxinfo.openid)
			{
				this.$toast('微信尚未完成授权,请授权完成后再来尝试');
				return;
			}
            var loading= this.$toast.loading({
              message: '正在绑定...',
              forbidClick: true,
            });
            _this.logining=true;
            this.axios.post('/public/login',{name:this.account,password:this.password,openid:this.wxinfo.openid,userinfo:JSON.stringify(this.wxinfo)}).then((res)=>{
                loading.clear();
                if(res.errno==0)
                {
                    var account = res.data;
                    _this.$store.commit('user/setToken',account.openid);
                    _this.$store.commit('user/setAccount',account);
                    _this.$toast('已成功与微信账户绑定');
					if(_this.$route.query.redirect){
					   let redirect = _this.getQueryString('redirect');
					   if(redirect.indexOf('_')>-1)
					   {
					       var name='',param = '',val='';
					       name =redirect.split('_')[0];
						   param=redirect.split('_')[1];
						   val=redirect.split('_')[2];
					       if(param=='tctnrId')
					       {
					           param='t_ctnrId';
					       }
					       var query = {};
					       query[param]=val;
						   setTimeout(function(){
							   _this.$router.replace({
							        path:'/'+name,
							        query:query
							   });
						   },1000)
					   }else{
						   setTimeout(function(){
							   _this.$router.replace({
							        path:'/'+redirect,
							   });
						   },1000)
					   }
					}else{
						setTimeout(function(){
							_this.$router.replace({
								path:'/profile'
							})
						},1500)
					}
                }else{
                    _this.logining=false;
                    _this.$toast.fail(res.errmsg);
                }
            }).catch((err)=>{
                _this.logining=false;
                loading.clear(); 
            })
        }
    },
    mounted:function(){
        var code=this.getQueryString('code');
		if(!this.openid)
		{	
			var innerredirect = this.$route.query.redirect;
			if(innerredirect)
			{
			    //处理从公众号直接访问某个具体的需要授权后才能访问的页面跳转
			    this.redirectUrl+=('?redirect='+innerredirect);
			}
			if(!code)
			{
			    this.getAuthCode();
			}else{
			    this.code=code;
			    this.getUserInfo();
			}
		}else{
			this.ifidentity=true;
			var _this=this;
			var loading = this.$toast.loading({
			  duration:60000,
			  message: '身份验证中...',
			  forbidClick: true,
			  loadingType: 'spinner'
			});
			this.axios.get('/home/getUserInfo').then((res)=>{
			    loading.clear();
			    if(res.errno==0)
			    {
					var account = res.data;
			        _this.$store.commit('user/setAccount',account);
					_this.$router.replace({
						path:'/profile'
					})
			    }else{
			       _this.$toast('当前账户尚未进行绑定,请完成绑定后再使用');
			    }
			}).catch((err)=>{
			    loading.clear();
			    _this.$toast.fail('获取数据失败');
			})
		}
    }
};
</script>

<style lang="less" scoped>
.login{
    width: 100%;
    height: auto;
    min-height: 100vh;
    background-image: url(../../assets/images/login.jpg);
    background-size: 100% 100%;
    background-repeat: no-repeat;
    border: 1px solid transparent;
    box-sizing: border-box;
	.wraper{
		width: 100%;
		height: auto;
		overflow: hidden;
		.tipwords{
			font-size: .46rem;
			color: #666;
			text-align: center;
			margin-top: 7rem;
		}
	}
    .tipinfo{
        font-size: .56rem;
        color: #666;
        margin-top: 1.5rem;
        .small{
            font-size: .4rem;
            margin-top: .4rem;
        }
    }
    .login_form{
        width: 100%;
        height: auto;
        margin-top: 2rem;
        .ipt_item{
            width: 70%;
            margin-left: 15%;
            height: auto;
            margin-top: 1rem;
            .logbtn{
                width: 100%;
            }
        }
    }
    .bot_tip{
        margin-top: 4rem;
        p{
            color: #999;
            font-size: .3rem;
            line-height: 1.6;
            margin-top: .2rem;
        }
    }
}
</style>
